<?php

function extract_zip($zipfile, $targetfolder)
{
    logging\info("extracting zip from %s to %s", $zipfile, $targetfolder);
    global $G_HAS_ZIP_COMMAND;
    if ($G_HAS_ZIP_COMMAND) {
        exec('unzip -o ' . $zipfile . ' -d ' . $targetfolder, $output, $res);
        if ($res != 0) {
            logging\error("cannot extract zip file %s", $zipfile);
            exit(1);    
        }
        return;
    }

    $zip = new ZipArchive;
    $res = $zip->open($zipfile);
    if ($res === true) {
        $zip->extractTo($targetfolder);
        $zip->close();
    } else {
        logging\error("cannot extract zip file %s", $zipfile);
        exit(1);
    }
}


function add_files_in_folder($zip, $folder, $base_folder)
{
    $dir = @opendir(join_paths($base_folder, $folder));
    while ($entry = readdir($dir)) {
        if ($entry == '.' || $entry == '..') continue;
        $relative_path = join_paths($folder, $entry);
        $absolute_path = join_paths($base_folder, $relative_path);
        if (is_dir($absolute_path)) {
            add_files_in_folder($zip, $relative_path, $base_folder);
        } else {
            $zip->addFile($absolute_path, $relative_path);
        }
    }
    closedir($dir);
}

function make_zip($zipfile, $folder)
{
    logging\info("compressing %s to %s", $folder, $zipfile);
    global $G_HAS_ZIP_COMMAND;
    if ($G_HAS_ZIP_COMMAND) {
        exec('cd "' . $folder . '" && zip -r ' . $zipfile . ' .', $output, $res);
        if ($res != 0) {
            logging\error("cannot create zip file %s", $zipfile);
            exit(1);    
        }
        return;
    }

    $zip = new ZipArchive;
    if ($zip->open($zipfile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        add_files_in_folder($zip, '', $folder);
        $zip->close();
    } else {
        logging\error("cannot create zip file %s", $zipfile);
        exit(1);
    }
}
